#!/usr/bin/env python

import itertools
import os
import time

TEMPLATE_FILE       = 'template.html'
DATA_DIR            = os.path.join(os.path.dirname(__file__), '../../../data/log/exercise/')
MINUTES_IN_A_HOUR   = 60
RECENT_DAYS         = 60 * 60 * 24 * 365 * 1.0 # year(s)

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


def mstr(m):
    return {
        1  : 'Jan', 2  : 'Feb', 3  : 'Mar', 4  : 'Apr', 5  : 'May', 6  : 'Jun',
        7  : 'Jul', 8  : 'Aug', 9  : 'Sep', 10 : 'Oct', 11 : 'Nov', 12 : 'Dec'}[m]
        
def bbody(req, user):
    control     = { 'bheader' : True, 'bbody' : True, 'bfooter' : True }
    hheader     = { }
    bbody       = None
    return_url  = None
    void        = { }

    params = { }

    # reading/parsing
    filenames = os.listdir(DATA_DIR)
    lines     = [ ]
    for filename in filenames:
        _lines = filter(lambda x : x[0] not in ('#', ' ', '\n'), 
                        open(os.path.join(DATA_DIR, filename), 'r').readlines())
        lines += _lines
    l  = map(lambda x : (map(int, 
                             x[0].split('-')), 
                         int(x[1])), 
             map(lambda x : x.split('\t'), 
                 lines))

    # grouping by yearly and monthly
    data_y = { }
    data_m = { }
    for year in range(2006, time.localtime()[0] + 1):
        data_y[year] = { 'sum' : sum(map(lambda x : x[1], 
                                         filter(lambda x : x[0][0] == year, 
                                                l))) / float(MINUTES_IN_A_HOUR), 
                         'last' : False,
                         'key'  : year }
    for x in l:
        y, m = time.gmtime(time.time() - RECENT_DAYS)[0:2]
        if (y, m) <= (x[0][0], x[0][1]):
            cym = (x[0][0], x[0][1])
            if not data_m.has_key(cym):
                data_m[cym] = { 'sum' : 0, 'last' : False }
            data_m[cym]['sum'] += (x[1] / float(MINUTES_IN_A_HOUR))
    data_y[sorted(data_y.keys())[-1]]['last'] = True
    data_m[sorted(data_m.keys())[-1]]['last'] = True

    # convert into list
    params['messages']         = map(lambda x : { 'key'  : x, 
                                                  'sum'  : '%4.2f' % data_y[x]['sum'], 
                                                  'last' : data_y[x]['last'] }, 
                                     sorted(data_y.keys()))

    params['messages_recents'] = map(lambda x : { 'key'  : '%s %s' % (mstr(x[1]), x[0]), 
                                                  'sum'  : '%4.2f' % data_m[x]['sum'], 
                                                  'last' : data_m[x]['last'] }, 
                                     sorted(data_m.keys()))

    # output
    path = os.path.join(os.path.dirname(__file__), TEMPLATE_FILE)
    bbody = template.render(path, params)      

    return (control, hheader, bbody, return_url, void)

